import csv
import time
import pymysql


def getCsvData(csv_file):
    file = open(file=csv_file, mode='r', encoding='utf-8-sig')
    # 把表格里面所有的数据读取,记录到reader对象
    reader = csv.reader(file)
    list = []
    for index, row in enumerate(reader, 1):
        list.append(row)
    return list


def getTime():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


class Logs():
    def __init__(self, path):
        self.path = path

    def info(self,val):
        file = open(self.path, mode="a", encoding="utf-8")
        file.write(f"\n{getTime()} [ info ] {val}")
        file.close()

    def error(self,val):
        file = open(self.path, mode="a", encoding="utf-8")
        file.write(f"\n{getTime()} [ error ] {val}")
        file.close()

    def debug(self,val):
        file = open(self.path, mode="a", encoding="utf-8")
        file.write(f"\n{getTime()} [ debug ] {val}")
        file.close()


class DBhelper():
    def __init__(self, **args):
        self.log = Logs('E:/py_project/re-fz/logs/logs.log')
        self.log.debug(args)
        self.dbConn = args

    def connect(self):
        try:
            self.conn = pymysql.connect(**self.dbConn, charset='utf8')
            self.cursor = self.conn.cursor()
        except Exception as result:
            print(result)
            self.log.error(f'数据库连接异常\n异常原因: {result}')

    def close(self):
        self.cursor.close()
        self.conn.close()

    def queryAll(self, sql, params=[]):
        data=None
        try:
            self.connect()
            self.cursor.execute(sql,params)
        except Exception as result:
            self.log.error(f'sql语句执行错误\nsql语句: {sql}\n参数:{params}\n错误信息:{result}')
        else:
            data = self.cursor.fetchall()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}\n查询结果：{data}')
        finally:
            self.close()
            return data

    def queryOne(self, sql, params=[]):
        data = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
        except Exception as result:
            self.log.err(f'sql语句执行错误\nsql语句：{sql}\n参数：{params}\n错误信息：{result}')
        else:
            data = self.cursor.fetchone()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}\n查询结果：{data}')
        finally:
            self.close()
            return data

    def update(self, sql, params=[]):
        count = 0
        try:
            self.connect()
            count = self.cursor.execute(sql, params)
        except Exception as result:
            self.conn.rollback()
            self.log.err(f'sql语句执行错误\nsql语句：{sql}\n参数：{params}\n错误信息：{result}')
        else:
            self.conn.commit()
            self.log.info(f'sql执行成功\nsql语句：{sql}\n参数：{params}')
        finally:
            self.close()
            return count






